﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using XLZF.MicroServices.IRepository;
using XLZF.MicroServices.Models;

namespace XLZF.MicroServices.ClothingDictService.Controllers;

/// <summary>
/// 衣物图片Api
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class ClothingPicesController : BaseController
{
    private readonly IClothingPicDictRepository _Repository;

    private readonly IConfiguration _configuration;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="clothingPicDictRepository"></param>
    public ClothingPicesController(IClothingPicDictRepository clothingPicDictRepository, IConfiguration configuration1)
    {
        _Repository = clothingPicDictRepository;

        _configuration = configuration1;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="chunkNumber"></param>
    /// <param name="chunkSize"></param>
    /// <param name="currentChunkSize"></param>
    /// <param name="totalSize"></param>
    /// <param name="identifier"></param>
    /// <param name="filename"></param>
    /// <param name="relativePath"></param>
    /// <param name="totalChunks"></param>
    /// <returns></returns>
    [HttpGet]
    [Route("[action]")]
    public IActionResult AddFiles(int chunkNumber, int chunkSize, int currentChunkSize, int totalSize, string identifier, string filename, string relativePath, int totalChunks)
    {
        Console.WriteLine("判断是否需要秒传");

        Console.WriteLine(chunkNumber + "|" + chunkSize + "|" + currentChunkSize + "|" + totalSize + "|" + identifier + "|" + filename + "|" + relativePath + "|" + totalChunks);

        return JsonView(true);
    }

    /// <summary>
    /// 添加文件
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    [HttpPost]
    [Route("[action]")]
    public Task<IActionResult> AddFiles([FromForm] UploadFiles request)
    {
        Console.WriteLine(request.totalSize + "|" + request.totalChunks + "|" + request.chunkSize + "|" + request.currentChunkSize + "|" + request.chunkNumber + "|" + request.filename + "|" + request.relativePath);

        try
        {
            if (request.file != null)
            {
                var file = request.file;

                var fileName = file.FileName;

                Stream? stream = file.OpenReadStream();

                //把stream转换成byte[]
                byte[] bytes = new byte[stream.Length];

                stream.Read(bytes, 0, bytes.Length);

                //设置当前流的位置为流的开始
                stream.Seek(0, SeekOrigin.Begin);

                string filenamediy = file.FileName.Split('.')[0] + "_" + request.chunkNumber + "." + file.FileName.Split('.')[1];

                var baseFilePath = _configuration.GetSection("baseFilePath").Value;

                //一次上传成功
                if (request.totalChunks == request.chunkNumber && request.totalChunks == 1)
                {
                    //把byte[]写入文件
                    FileStream fs = new FileStream(baseFilePath + fileName, FileMode.Create);

                    BinaryWriter bw = new BinaryWriter(fs);

                    bw.Write(bytes);

                    bw.Close();

                    fs.Close();

                    return Task.FromResult(JsonView(new ResultModel { needMerge = 0 }));
                }
                else
                {

                    var baseFilePath_dir = baseFilePath + file.FileName.Split('.')[0] + "\\";

                    //切片上传
                    if (request.chunkNumber == 1)
                    {
                        //在指定的根目录创建专属临时文件夹
                        Common.FileHelper.CreateDir(baseFilePath_dir);
                    }

                    //把byte[]写入文件
                    FileStream fs = new FileStream(baseFilePath_dir + filenamediy, FileMode.Create);

                    BinaryWriter bw = new BinaryWriter(fs);

                    bw.Write(bytes);

                    bw.Close();

                    fs.Close();

                    return Task.FromResult(JsonView(new ResultModel { needMerge = 1, DirName = baseFilePath_dir, FileName = baseFilePath + fileName }));
                }
            }
            else
            {
                return Task.FromResult(JsonView(false));
            }
        }
        catch (Exception ex)
        {
            return Task.FromResult(JsonView(ex.Message));
        }
    }

    /// <summary>
    /// 合并
    /// </summary>
    /// <param name="result"></param>
    /// <returns></returns>
    [HttpPost]
    [Route("[action]")]
    public Task<IActionResult> HeBing([FromBody] ResultModel result)
    {
        if (!string.IsNullOrEmpty(result.DirName) && Directory.Exists(result.DirName) && !string.IsNullOrEmpty(result.FileName))
        {
            var files = Directory.GetFiles(result.DirName);

            if (files.Length > 0)
            {
                //合并
                Common.FileHelper.CombineFile(files, result.FileName);

                //删除
                Common.FileHelper.DelectDir(result.DirName);

                return Task.FromResult(JsonView(true));
            }
            else
            {
                return Task.FromResult(JsonView(result.DirName + "文件夹内没有文件"));
            }
        }
        else
        {
            return Task.FromResult(JsonView("请检查是否存在文件夹或者指定文件名称是否为空！"));
        }
    }
}

